#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <fstream>

#include "FlvParser.h"

void process(std::fstream &fin, const char * fileName) {
    FlvParser parser;

    int bufSize = 2 * 1024 * 1024;
    int flvPos = 0;
    uint8_t *pBuf, *pBak;
    pBuf = new uint8_t[bufSize];
    pBak = new uint8_t[bufSize];

    while (1) {
        int readNum = 0;
        int usedLen = 0;
        fin.read((char *)pBuf + flvPos, bufSize - flvPos);
        readNum = fin.gcount();

        if (readNum == 0)
            break;

        flvPos += readNum;

        parser.parse(pBuf, flvPos, usedLen);
        if (flvPos != usedLen) {
            memcpy(pBak, pBuf + usedLen, flvPos - usedLen);
            memcpy(pBuf, pBak, flvPos - usedLen);
        }
        flvPos -= usedLen;
    }

    parser.printInfo();
    parser.dumpH264("parser.264");
    parser.dumpAAC("parser.aac");

    //dump int flv
    parser.dumpFlv(fileName);

    delete []pBak;
    delete []pBuf;
}

int main(int argc, char *argv[])
{
    std::cout << "This is FLV parser test program." << std::endl;

    if (argc != 3) {
        std::cout << "FlvParser.exe [input flv] [output flv]" << std::endl;
        return 0;
    }

    std::fstream fin;
    fin.open(argv[1], std::ios_base::in | std::ios_base::binary);
    if (!fin)
        return 1;

    process(fin, argv[2]);

    fin.close();

    return 0;
}
